import {getSingleton, singleton} from "../../../utils/SingletonUtils";
import {BaseContext, Constructor} from "../../../utils/BaseContext";

const UpdateInterval = 20; // 更新间隔

@singleton
export class ManagerContext extends BaseContext {

	get contentName(): string { return "Manager"; }

	public update() {
		this.contents.forEach(c => c.value?.update());
	}

}

export function manager<T extends BaseManager>(
	clazz: Constructor<T>) {
	managerContext().create(clazz, new clazz());
	return clazz;
}

/*
@singleton
export class ManagerContext {

	public managers = {};

	public createManager<T extends BaseManager>(
		clazz: Constructor<T>){
		if (clazz) this.managers[clazz.name] = new clazz();

		console.error("[CREATE] ", {clazz, this: this});
	}

	public update() {
		for (const key in this.managers)
			this.managers[key].update();
	}

	public instance<T extends BaseManager>(
		clazz: Constructor<T> | string) : T {
		if (!clazz) return null;

		const res = typeof clazz == 'string' ?
			this.managers[clazz] : this.instance(clazz.name);

		if (!res) console.error("[GET] ", {clazz, res, this: this});

		return res;

		// if (typeof clazz == 'string')
		// 	return this.managers[clazz];
		// return this.instance(clazz.name);
	}

}

export function manager<T extends BaseManager>(
	clazz: Constructor<T>) {
	managerContext().createManager(clazz);
	return clazz;
}
*/


// export function useManager<T extends BaseManager>(
// 	clazz: Constructor<T> | string) {
// 	// const ctx = ManagersContext.Get();
// 	const ctx = SingletonUtils.instance(ManagersContext);
// 	return (target, key) => {
// 		console.log("[USE] ", {clazz, target, key});
// 		target[key] = ctx.instance(clazz);
// 	};
// }

function managerContext() {
	return getSingleton(ManagerContext);
}

export function getManager<T extends BaseManager>(
	clazz: Constructor<T>) {
	return managerContext().instance(clazz);
}

function updateContext() {
	managerContext().update();
}
setInterval(updateContext, UpdateInterval);

export class BaseManager {

	public update() { }

}
